package com.tjetc.controller;

import com.tjetc.common.CodeUtil;
import com.tjetc.common.JsonResult;
import com.tjetc.entity.User;
import com.tjetc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("userlogin")
public class UserLoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private CodeUtil codeUtil;

    /***
     * 用户登录
     * @param username
     * @param password
     * @param code
     * @param session
     * @return
     */
    @RequestMapping("login")
    public JsonResult adminLogin(@RequestParam("username") String username,
                                 @RequestParam("password") String password,
                                 @RequestParam("code") String code,
                                 HttpSession session) {
        String session_code = (String) session.getAttribute("code");
        // 首先检查验证码是否正确(不区分大小写)
        if(!session_code.equalsIgnoreCase(code)) {
            return new JsonResult<>(1, "验证码不正确", null);
        }
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        session.setAttribute("user",username);
        return userService.login(user);
    }

    /***
     * 登录页面获取验证码
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("get") // 用于获取验证码
    public JsonResult handleCode(HttpSession session) throws Exception {
        String code = codeUtil.generateCaptcha();
        byte[] bytes =  codeUtil.generateCaptchaImage(code);
        session.setAttribute("code", code);
        return new JsonResult<>(0, "", bytes);
    }
}